package com.jml.zlhq.app.ui;

import java.util.HashMap;
import java.util.Map;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import com.jml.zlhq.app.BuildConfig;
import com.jml.zlhq.app.R;
import com.jml.zlhq.app.util.StringUtil;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.DownloadListener;
import android.webkit.JavascriptInterface;
import android.webkit.JsPromptResult;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.AutoCompleteTextView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

@SuppressWarnings("deprecation")
public class CommonWebActivity extends BaseActivity {
	private WebView webView;
	private LinearLayout loadpage;
	private TextView loadText;
	private String url;
	private Handler handler = new Handler() {  
        @Override  
        public void handleMessage(Message msg) {  
            if(msg.what!=200) {//主页不存在  
            	//载入本地assets文件夹下面的错误提示页面404.html  
            	loadText.setText("很抱歉，出错啦！"); 
            } else {  
            	int version = 1;
            	try { 
                 	PackageInfo info = CommonWebActivity.this.getPackageManager().getPackageInfo(CommonWebActivity.this.getPackageName(), 0);
                 	version = info.versionCode;
            	} catch (NameNotFoundException e) {    
         			e.printStackTrace(System.err);
         		} 
            	Map<String,String> extraHeaders = new HashMap<String, String>();
                extraHeaders.put("51zlhq-app", String.valueOf(version));
                webView.loadUrl(url,extraHeaders);  
            }  
        }  
	}; 
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.common_web_activity);
		
		LinearLayout leftLay = (LinearLayout) findViewById(R.id.content_header_left_lay);
		@SuppressWarnings("unused")
		LinearLayout rightLay = (LinearLayout) findViewById(R.id.content_header_right_lay);
		leftLay.setOnClickListener(this);
		AutoCompleteTextView centerEdit = (AutoCompleteTextView) findViewById(R.id.content_header_center_edit);
		centerEdit.setVisibility(View.GONE);
		ImageView leftImage = (ImageView) findViewById(R.id.content_header_left_img);
		leftImage.setImageResource(R.drawable.back_selector);
		ImageView roghtImage1 = (ImageView) findViewById(R.id.content_header_right_img);
		roghtImage1.setVisibility(View.INVISIBLE);
		TextView centerText = (TextView) findViewById(R.id.content_header_center_text);
		centerText.setText("赚零花钱");
		TextView rightText = (TextView) findViewById(R.id.content_header_right_text);
		rightText.setVisibility(View.INVISIBLE);
		TextView cityChosed = (TextView) findViewById(R.id.content_header_center_text2);
		cityChosed.setVisibility(View.GONE);
		loadpage = (LinearLayout)findViewById(R.id.load_info_lay);
		loadText = (TextView) findViewById(R.id.load_info);
		loadpage.setVisibility(View.VISIBLE);
		
		ImageView spaceshipImage = new ImageView(this);
		spaceshipImage.setImageResource(R.drawable.publicloading);
		Animation hyperspaceJumpAnimation = AnimationUtils.loadAnimation(this, R.anim.loading_animation);
		loadpage.addView(spaceshipImage, 0);
		spaceshipImage.startAnimation(hyperspaceJumpAnimation);
		
		webView = (WebView) findViewById(R.id.common_web);
		
		this.initWebView();
		
		//if()
		//if(crowdUrl!=null&&crowdUrl.contains("/map"))crowdUrl = "http://192.168.1.254:8080/"+crowdUrl.substring(crowdUrl.indexOf("/map"));
		try {
			url = getIntent().getExtras().getString("url");
		} catch (Exception e) {
			e.printStackTrace();
		}
		if(!StringUtil.isEmpty(url)&&appContext.isLogin()){
			if(BuildConfig.DEBUG){
				Log.i("===web url===", url);
			}
			
		}
		new Thread(new Runnable() {  
            @Override  
            public void run() {  
                    Message msg = new Message();  
                    //此处判断主页是否存在，因为主页是通过loadUrl加载的，  
                    //此时不会执行shouldOverrideUrlLoading进行页面是否存在的判断  
                    //进入主页后，点主页里面的链接，链接到其他页面就一定会执行shouldOverrideUrlLoading方法了  
                    msg.what = getRespStatus(url);  
                    handler.sendMessage(msg);  
            }  
		}).start();  
		
		// 用JavaScript调用Android函数：
		// 先建立桥梁类，将要调用的Android代码写入桥梁类的public函数
		// 绑定桥梁类和WebView中运行的JavaScript代码
		// 将一个对象起一个别名传入，在JS代码中用这个别名代替这个对象，可以调用这个对象的一些方法
		webView.addJavascriptInterface(new WebAppInterface(this), "appInterface");
	}

	@Override
	public void loadData(Map<String, String> param) {}

	@Override
	public void clearData() {}
	
	@SuppressLint("SetJavaScriptEnabled")
	private void initWebView(){
		// 得到设置属性的对象
		WebSettings webSettings = webView.getSettings();
		// 使能JavaScript
		webSettings.setJavaScriptEnabled(true);
		// 支持中文，否则页面中中文显示乱码
		webSettings.setDefaultTextEncodingName("UTF-8");
        webSettings.setSaveFormData(false);  
        webSettings.setSupportZoom(false);  
        webSettings.setBlockNetworkImage(true);
		//clearCach(webView);
		// 限制在WebView中打开网页，而不用默认浏览器
        webView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY); 
		webView.setWebViewClient(new WebViewClient());
		// 如果不设置这个，JS代码中的按钮会显示，但是按下去却不弹出对话框
		// Sets the chrome handler. This is an implementation of WebChromeClient
		// for use in handling JavaScript dialogs, favicons, titles, and the
		// progress. This will replace the current handler.
		webView.setWebChromeClient(new EXWebChromeClient());
		webView.setDownloadListener(new MyWebViewDownLoadListener());  
	}

	protected void clearCach(WebView webView) {
		webView.clearCache(true); 
		CookieSyncManager.createInstance(this);
		CookieManager cookieManager = CookieManager.getInstance();
		cookieManager.removeAllCookie();
		CookieManager.getInstance().removeSessionCookie();
		CookieSyncManager.getInstance().sync();
		CookieSyncManager.getInstance().startSync();
	}

	@Override
	public void onClick(View view) {
		switch (view.getId()) {
		case R.id.content_header_left_lay:
			finish();
			break;
		default:
			break;
		}
	}
	
	/** 
     * 继承WebChromeClient类 
     * 对js弹出框时间进行处理 
     *  
     */  
    private class EXWebChromeClient extends WebChromeClient {  
  
        /** 
         * 处理alert弹出框 
         */  
        @Override  
        public boolean onJsAlert(WebView view,String url, String message, JsResult result) {  
//            mReusultText.setText("Alert:"+message);  
//            //对alert的简单封装  
//            new AlertDialog.Builder(WebViewDemo.this).  
//                setTitle("Alert").setMessage(message).setPositiveButton("OK",  
//                new DialogInterface.OnClickListener() {  
//                    @Override  
//                    public void onClick(DialogInterface arg0, int arg1) {  
//                       //TODO  
//                   }  
//            }).create().show();  
//            result.confirm();  
            return super.onJsAlert(view, url, message, result);  
        }  
  
        /** 
         * 处理confirm弹出框 
         */  
        @Override  
        public boolean onJsConfirm(WebView view, String url, String message, JsResult result) {  
//            mReusultText.setText("Confirm:"+message);  
//            result.confirm();  
            return super.onJsConfirm(view, url, message, result);  
        }  
  
        /** 
         * 处理prompt弹出框 
         */  
        @Override  
        public boolean onJsPrompt(WebView view, String url, String message, String defaultValue, JsPromptResult result) {  
//            mReusultText.setText("Prompt input is :"+message);  
//            result.confirm();  
            return super.onJsPrompt(view, url, message, message, result);  
        }  
        
        public void onProgressChanged(WebView view,int newProgress){
        	loadText.setText("玩命加载中\t"+newProgress+"%");
        	if(newProgress>=100){
        		loadpage.setVisibility(View.GONE);
        		webView.getSettings().setBlockNetworkImage(false);
        	}
        }
    }  
	
	/**
	 * 自定义的Android代码和JavaScript代码之间的桥梁类
	 * 
	 * @author 1
	 * 
	 */
	public class WebAppInterface {
		Context mContext;

		/** Instantiate the interface and set the context */
		WebAppInterface(Context c) {
			mContext = c;
		}

		/** Show a toast from the web page */
		// 如果target 大于等于API 17，则需要加上如下注解window.thirdLogin.login(param)
		@JavascriptInterface
		public void method(String type, String id) {
			
		}
	}

	private int getRespStatus(String url) {  
        int status = -1;  
        try {  
                HttpGet head = new HttpGet(url);  
                HttpClient client = new DefaultHttpClient();  
                HttpResponse resp = client.execute(head);  
                status = resp.getStatusLine().getStatusCode();  
        } catch (Exception e) {}  
        return status;  
	} 
	
	private class MyWebViewDownLoadListener implements DownloadListener{   
        @Override  
        public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype,   
                                    long contentLength) {              
            Log.i("tag", "url="+url);              
            Log.i("tag", "userAgent="+userAgent);   
            Log.i("tag", "contentDisposition="+contentDisposition);            
            Log.i("tag", "mimetype="+mimetype);   
            Log.i("tag", "contentLength="+contentLength);   
            Uri uri = Uri.parse(url);   
            Intent intent = new Intent(Intent.ACTION_VIEW, uri);   
            startActivity(intent);              
        }   
    } 
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		return super.onKeyDown(keyCode, event);
	}
}
